"""
   ┌─┐       ┌─┐ + +
┌──┘ ┴───────┘ ┴──┐++
│                 │
│       ───       │++ + + +
███████───███████ │+
│                 │+
│       ─┴─       │
│                 │
└───┐         ┌───┘
    │         │
    │         │   + +
    │         │
    │         └──────────────┐
    │                        │
    │                        ├─┐
    │                        ┌─┘
    │                        │
    └─┐  ┐  ┌───────┬──┐  ┌──┘  + + + +
      │ ─┤ ─┤       │ ─┤ ─┤
      └──┴──┘       └──┴──┘  + + + +
             神兽保佑
            代码无BUG!
"""
import time

import pymysql
import requests

from operating_sql import SQLManager


class TopApi:
    def __init__(self):
        self.url = "http://apis.5118.com/wyc/akey"
        self.headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "8CD1BAC882C24F86A8D8F0E2A7B0FF45"
        }
        self.data = {
            "txt": "",
            "th": 6
        }
        self.all_content = []
        self.sql = SQLManager()

    def read_sql(self):
        sql_cx = "select * from weibo where id > 0"
        self.all_content = self.sql.get_tuple_more(sql_cx)
        print(len(self.all_content))

    def post_api(self):
        for info in self.all_content:
            content = info[3]
            self.data["txt"] = content
            time.sleep(0.5)
            json_ = requests.post(self.url, headers=self.headers, data=self.data).json()
            if json_["errcode"] == "2005050":
                print(json_)
                continue
            elif json_["errcode"] == "100102":
                time.sleep(1)
                print(json_)
                continue
            try:
                txt = json_["data"]
                update_sql = 'update weibo set content="%s" where id="%s"' % (pymysql.escape_string(txt), info[0])
                self.sql.run(update_sql)
                print(info[0])
            except:
                print(json_)

    def run(self):
        self.read_sql()
        self.post_api()


if __name__ == '__main__':
    top = TopApi()
    top.run()
